package com.strawberry.chat2.views.neteasePlayer;

import android.net.Uri;
import android.util.Log;
import android.view.View;

import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.uimanager.ThemedReactContext;
import com.strawberry.chat2.views.neteasePlayer.core.view.IRenderView;
import com.strawberry.chat2.views.neteasePlayer.sdk.LivePlayer;
import com.strawberry.chat2.views.neteasePlayer.sdk.LivePlayerObserver;
import com.strawberry.chat2.views.neteasePlayer.sdk.PlayerManager;
import com.strawberry.chat2.views.neteasePlayer.sdk.constant.CauseCode;
import com.strawberry.chat2.views.neteasePlayer.sdk.model.MediaInfo;
import com.strawberry.chat2.views.neteasePlayer.sdk.model.StateInfo;
import com.strawberry.chat2.views.neteasePlayer.sdk.model.VideoBufferStrategy;
import com.strawberry.chat2.views.neteasePlayer.sdk.model.VideoOptions;
import com.strawberry.chat2.views.neteasePlayer.sdk.model.VideoScaleMode;
import com.strawberry.chat2.views.neteasePlayer.sdk.view.AdvanceTextureView;
import com.netease.neliveplayer.sdk.NELivePlayer;

public class neteasePlayerView extends AdvanceTextureView {
    private final static String TAG = "neteasePlayerView";
    private String mMediaType = "livestream";
    private String mDecodeType = "hardware";//解码类型，硬解或软解
    private boolean mHardware = true;
    private String mVideoPath;
    private Uri mUri;
    private LivePlayer player;
    private MediaInfo mediaInfo;
    private View mBuffer; //用于指示缓冲状态
//    private AdvanceTextureView advanceTextureView;
//    private boolean isAdvanceTextureViewDestory;
    protected boolean isPauseInBackgroud = false;//直播进入后台停止播放
    private final ThemedReactContext themedReactContext;

    public neteasePlayerView(ThemedReactContext context) {
        super(context);
        this.themedReactContext = context;
    }

    public void setSrc(String uri) {
        this.mVideoPath = uri;
        this.mUri = Uri.parse(mVideoPath);
        this.initPlayer();
    }

    private void initPlayer() {
        VideoOptions options = new VideoOptions();
        options.hardwareDecode = mHardware;

        /**
         * isPlayLongTimeBackground 控制退到后台或者锁屏时是否继续播放，开发者可根据实际情况灵活开发,我们的示例逻辑如下：
         * 使用软件解码：
         * isPlayLongTimeBackground 为 false 时，直播进入后台停止播放，进入前台重新拉流播放
         * isPlayLongTimeBackground 为 true 时，直播进入后台不做处理，继续播放,
         *
         * 使用硬件解码：
         * 直播进入后台停止播放，进入前台重新拉流播放
         */
        options.isPlayLongTimeBackground = isPauseInBackgroud;

        options.bufferStrategy = VideoBufferStrategy.LOW_LATENCY;
        player = PlayerManager.buildLivePlayer(themedReactContext.getBaseContext(), mVideoPath, options);

        start();

        player.setupRenderView(this, VideoScaleMode.FIT);
    }

    public void releaselayer() {
        if (player == null) {

            return;
        }

        Log.i(TAG, "releasePlayer");

        player.registerPlayerObserver(playerObserver, false);
        player.setupRenderView(null, VideoScaleMode.NONE);
        this.releaseSurface();
        player.stop();
        player = null;
    }

    private void start() {
        player.registerPlayerObserver(playerObserver, true);

//        player.registerPlayerCurrentSyncTimestampListener(pullIntervalTime, mOnCurrentSyncTimestampListener, true);
//        player.registerPlayerCurrentSyncContentListener(mOnCurrentSyncContentListener, true);

        player.start();
    }

    //这里直播可以用 LivePlayerObserver 点播用 VodPlayerObserver
    private LivePlayerObserver playerObserver = new LivePlayerObserver() {

        @Override
        public void onPreparing() {
            Log.d(TAG, "onPreparing");
        }

        @Override
        public void onPrepared(MediaInfo info) {
            mediaInfo = info;
        }

        @Override
        public void onError(int code, int extra) {
            Log.d(TAG, "视频解析出错");
        }

        @Override
        public void onFirstVideoRendered() {
            Log.d(TAG, "视频第一帧已解析");
            themedReactContext
                    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit("onRtmpFinish", null);
        }

        @Override
        public void onFirstAudioRendered() {
//            showToast("音频第一帧已解析");

        }

        @Override
        public void onBufferingStart() {
            Log.d(TAG, "onBufferingStart");
            mBuffer.setVisibility(View.VISIBLE);
        }

        @Override
        public void onBufferingEnd() {
            Log.d(TAG, "onBufferingEnd");
            mBuffer.setVisibility(View.GONE);
        }

        @Override
        public void onBuffering(int percent) {
            Log.d(TAG, "缓冲中..." + percent + "%");
        }

        @Override
        public void onHardwareDecoder(int value) {
            Log.d(TAG, "使用解码类型：" + (value == 1 ? "硬件解码" : "软解解码"));
        }

        @Override
        public void onStateChanged(StateInfo stateInfo) {
            if(stateInfo!=null &&stateInfo.getCauseCode() ==  CauseCode.CODE_VIDEO_STOPPED_AS_NET_UNAVAILABLE) {
                Log.d(TAG, "网络已断开");
            }
        }

        @Override
        public void onVideoFrameFilter(NELivePlayer.NEVideoRawData videoRawData) {

        }

        @Override
        public void onAudioFrameFilter(NELivePlayer.NEAudioRawData audioRawData) {

        }

        @Override
        public void onHttpResponseInfo(int code, String header) {
            Log.i(TAG, "onHttpResponseInfo,code:" + code + " header:" + header);
        }
    };

}
